package com.kbt.service;



import android.app.*;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import cn.jpush.android.api.BasicPushNotificationBuilder;
import cn.jpush.android.api.JPushInterface;
import com.kbt.activity.GoodInfoActivity;
import com.kbt.activity.R;
import com.kbt.activity.StoreActivity;
import com.kbt.activity.TeMaiKaiQiangActivity;
import com.kbt.base.BaseApplication;
import org.json.JSONObject;

import java.util.List;

/**
 * 自定义接收器
 * 
 * 如果不定义这个 Receiver，则： 1) 默认用户会打开主界面 2) 接收不到自定义消息
 */
public class MyReceiver extends BroadcastReceiver {
	private static final String TAG = "JPush";
	private static String extraString = "";
	private boolean isAppRunning = false;

	@Override
	public void onReceive(Context context, Intent intent) {
		Bundle bundle = intent.getExtras();
		Log.d(TAG + "1", "[MyReceiver] onReceive - " + intent.getAction()
				+ ", extras: " + printBundle(bundle));

		if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) {
			String regId = bundle
					.getString(JPushInterface.EXTRA_REGISTRATION_ID);
			Log.d(TAG + "2", "[MyReceiver] 接收Registration Id : " + regId);
			// send the Registration Id to your server...

		} else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent
				.getAction())) {
			Log.d(TAG + "3",
					"[MyReceiver] 接收到推送下来的自定义消息: "
							+ bundle.getString(JPushInterface.EXTRA_MESSAGE));
			String msg_type="";//消息类型
			String msg_title="";//消息标题
			String msg_content="";//消息内容
			String msg_id="";//消息ID
			String msg_ext="";//消息扩展
			Intent intent1=null;
			JPushInterface.reportNotificationOpened(context,
					bundle.getString(JPushInterface.EXTRA_MESSAGE));
			JSONObject json1 = null;
			try {
				Log.e("extraString",extraString);
				if (extraString.equals("{}") || "".equals(extraString)) {
						Intent in = context.getPackageManager().getLaunchIntentForPackage("com.kbt.activity");
						context.startActivity(in);
				} else {
					ActivityManager am = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
					List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(100);
					for (ActivityManager.RunningTaskInfo info : list) {
						if (info.topActivity.getPackageName().equals("com.kbt.activity") && info.baseActivity.getPackageName().equals("com.kbt.activity")) {
							isAppRunning = true;
							//find it, break
							break;
						}
					}
					if(!isAppRunning){
						Intent in = context.getPackageManager().getLaunchIntentForPackage("com.kbt.activity");
						context.startActivity(in);
					}

				}
				json1 = new JSONObject(extraString);
				msg_type = json1.getString("msg_type");
				msg_title = json1.getString("msg_title");
				msg_content = json1.getString("msg_content");
				msg_id = json1.getString("msg_id");
				NotificationManager manager = null;
				if (context != null) {
					manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
				}
				if (msg_type.equals("news")) {
					Log.e("新闻", "新闻");
				} else if (msg_type.equals("active")) {

				} else if (msg_type.equals("商品")) {
					intent1 = new Intent(context, GoodInfoActivity.class);
					intent1.putExtra("shopId", msg_id);
				} else if (msg_type.equals("通知")) {
					Log.e("通知", "通知");
				}
				PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,
						intent1, PendingIntent.FLAG_UPDATE_CURRENT);
				Notification notify1 = new Notification();
				notify1.icon = R.drawable.ic_lancher;
				notify1.tickerText = "您有新短消息，请注意查收！";
				notify1.when = System.currentTimeMillis();
				notify1.setLatestEventInfo(context, msg_title,
						msg_content, pendingIntent);
				notify1.defaults |= Notification.DEFAULT_VIBRATE;
				long[] vibrate = {0, 100, 200, 300};
				notify1.vibrate = vibrate;
//				    notify1.number = 1;
				notify1.flags |= Notification.FLAG_AUTO_CANCEL;
				manager.notify(1, notify1);

			}catch (Exception e){
				e.printStackTrace();
			}

		} else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent
				.getAction())) {
			Log.d(TAG, "[MyReceiver] 接收到推送下来的通知");
			int notifactionId = bundle
					.getInt(JPushInterface.EXTRA_NOTIFICATION_ID);
			Log.d(TAG, "[MyReceiver] 接收到推送下来的通知的ID: " + notifactionId);

		} else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent
				.getAction())) {
			Log.d(TAG, "[MyReceiver] 用户点击打开了通知");
			JPushInterface.reportNotificationOpened(context,
					bundle.getString(JPushInterface.EXTRA_MSG_ID));
//			if (extraString.equals("{}") || "".equals(extraString)) {
//					Intent in = context.getPackageManager().getLaunchIntentForPackage("com.kbt.activity");
//					context.startActivity(in);
//			}else{
				ActivityManager am = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
				List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(100);
				for (ActivityManager.RunningTaskInfo info : list) {
					if (info.topActivity.getPackageName().equals("com.kbt.activity") && info.baseActivity.getPackageName().equals("com.kbt.activity")) {
						isAppRunning = true;
						//find it, break
						break;
					}
				}
				if(!isAppRunning){
					Intent in = context.getPackageManager().getLaunchIntentForPackage("com.kbt.activity");
					context.startActivity(in);
				}
//			}

		}

	}

	// 打印所有的 intent extra 数据
	private static String printBundle(Bundle bundle) {
		StringBuilder sb = new StringBuilder();
		for (String key : bundle.keySet()) {
			if (key.equals(JPushInterface.EXTRA_NOTIFICATION_ID)) {
				sb.append("\nkey:" + key + ", value:" + bundle.getInt(key));
			} else if (key.equals(JPushInterface.EXTRA_CONNECTION_CHANGE)) {
				sb.append("\nkey:" + key + ", value:" + bundle.getBoolean(key));
			} else if (key.equals("cn.jpush.android.EXTRA")) {
				extraString = bundle.getString(key);
				   Log.w("xxxxx", extraString);
			} else {
				sb.append("\nkey:" + key + ", value:" + bundle.getString(key));
			}
		}
		return sb.toString();
	}

}
